package com.kla.power.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kla.power.entity.*;
import com.kla.power.mapper.*;
import com.kla.power.service.ILatestInverterElectricService;
import com.kla.power.service.IStationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kla.power.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.temporal.ChronoField;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 发电站表 服务实现类
 * </p>
 * @author WuZH
 * @since 2024-06-02
 */
@Service
public class StationServiceImpl extends ServiceImpl<StationMapper, StationEntity> implements IStationService {

    @Resource
    private StationMapper stationMapper;
    @Resource
    private DeviceMapper deviceMapper;
    @Resource
    private InverterElectricMapper inverterElectricMapper;
    @Resource
    private InverterAmountStatisticsDayMapper inverterAmountStatisticsDayMapper;
    @Resource
    private AlarmMapper alarmMapper;
    @Resource
    private ILatestInverterElectricService iLatestInverterElectricService;
    @Resource
    private LatestInverterElectricMapper latestInverterElectricMapper;

    /**
     * 查询电站列表，同时获取电站下属所有设备的发电相关数据，不涵盖子系统(电站)的设备
     * @param stationEntity
     * @return
     */
    @Override
    public List<StationEntity> queryList (StationEntity stationEntity) {
        if ( stationEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        stationEntity.setPage ( ( stationEntity.getPage () - 1 ) * stationEntity.getLimit () );
        List<StationEntity> stationEntities = stationMapper.queryList ( stationEntity );
        //在外面求电站的报警情况，根据电站Id匹配上去
        List<AlarmEntity> alarmEntities = null;
        if ( stationEntities != null && stationEntities.size () > 0 ) {
            List<String> stationIds = stationEntities.stream ().map ( StationEntity :: getId ).collect ( Collectors.toList () );
            alarmEntities = alarmMapper.queryAlarmCountByStation ( stationIds );
        }
        //所有电站所有逆变器当天发电最后一组数据
        //List<InverterElectricEntity> inverterElectricEntities = inverterElectricMapper.queryInverterElectricEntities ();
        List<LatestInverterElectricEntity> list = iLatestInverterElectricService.list ();
        //求所有电站的所有逆变器的装机容量
        List<DeviceEntity> deviceEntities = deviceMapper.selectList ( new LambdaQueryWrapper<DeviceEntity> ().eq ( DeviceEntity :: getDeviceType, 2 ) );
        for ( StationEntity station : stationEntities ) {
            // 获取下属设备离线和报警
            double allActivePower = 0; // 该电站总的发电功率
            double dayPower = 0;
            double power = 0;
            double todayEnergy = 0;
            //每个电站的警告数量
            if ( alarmEntities != null && alarmEntities.size () > 0 ) {
                List<AlarmEntity> collect = alarmEntities.stream ().filter ( detail -> detail.getStationId ().equals ( station.getId () ) ).collect ( Collectors.toList () );
                station.setAlarmFlag ( collect.size () );
            }
            if ( list != null && list.size () > 0 ) {
                List<LatestInverterElectricEntity> ins = list.stream ().filter ( i -> station.getId ().equals ( i.getStationId () ) ).collect ( Collectors.toList () );
                if ( ins != null && ins.size () > 0 ) {
                    for ( LatestInverterElectricEntity device : ins ) {
                        if ( StringUtils.isNotBlank ( device.getGridPower () ) ) {
                            allActivePower += Double.parseDouble ( device.getGridPower () );
                            // 只统计今天的发电量
                            if ( CommonUtil.checkDay ( CommonUtil.getDateStrFormat ( device.getUpdateTime (), "yyyy-MM-dd" ) ) ) {
                                dayPower += ( device != null ? Double.parseDouble ( device.getTodayEnergy () ) : 0 );
                            }
                        }
                        //统计装机容量
                        //power += Double.parseDouble ( ( null == device.getPower () || "".equals ( device.getPower () ) ) ? "0" : device.getPower () );
                        //当日发电量之和
                        todayEnergy += Double.parseDouble ( StringUtils.isBlank ( device.getTodayEnergy () ) ? "0" : device.getTodayEnergy () );
                    }
                }
            }
            //处理装机容量
            if ( deviceEntities != null && deviceEntities.size () > 0 ) {
                List<DeviceEntity> collect = deviceEntities.stream ().filter ( d -> StringUtils.isNotBlank ( d.getStationId () ) && d.getStationId ().equals ( station.getId () ) ).collect ( Collectors.toList () );
                if ( collect != null && collect.size () > 0 ) {
                    //统计装机容量
                    power = collect.stream ().mapToDouble ( device -> Double.parseDouble ( StringUtils.isBlank ( device.getPower () ) ? "0" : device.getPower () ) ).sum ();
                }
            }
            station.setCapacity ( CommonUtil.parseDecimalPoint ( power ) );
            station.setGridPower ( CommonUtil.parseDecimalPoint ( Double.parseDouble ( CommonUtil.parseDecimalPoint ( allActivePower ) ) / 1000 ) );
            station.setTodayEnergy ( CommonUtil.parseDecimalPoint ( dayPower ) );
            String v = CommonUtil.divided ( Double.parseDouble ( StringUtils.isBlank ( station.getGridPower () ) ? "0" : station.getGridPower () ), power );
            station.setAvgActivePower ( v ); //计算公式：功率归一化=当前发电功率/装机容量
            station.setTodayEnergy ( CommonUtil.parseDecimalPoint ( todayEnergy ) );
            String full = CommonUtil.divided ( Double.parseDouble ( StringUtils.isBlank ( station.getTodayEnergy () ) ? "0" : station.getTodayEnergy () ), Double.parseDouble ( StringUtils.isBlank ( station.getCapacity () ) ? "0" : station.getCapacity () ) );
            station.setFullHour ( full ); //满发小时=发电量/装机容量
        }
        return stationEntities;
    }


    @Override
    public Integer queryCount (StationEntity stationEntity) {
        if ( stationEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        Integer integer = stationMapper.queryCount ( stationEntity );
        return integer;
    }

    @Override
    public StationEntity saveSingle (StationEntity stationEntity) {
        if ( stationEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        if ( StringUtils.isBlank ( stationEntity.getId () ) ) {
            throw new StateException ( StateEnum.PRIMARY_NULL_EXCE );
        }
        stationEntity.setCreateTime ( new Date () );
        int insert = baseMapper.insert ( stationEntity );
        if ( insert == 0 ) {
            throw new StateException ( StateEnum.INSERT_EXCE );
        }
        return stationEntity;
    }

    @Override
    public StationEntity querySingle (StationEntity stationEntity) {
        if ( stationEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        if ( StringUtils.isBlank ( stationEntity.getId () ) ) {
            throw new StateException ( StateEnum.PRIMARY_NULL_EXCE );
        }
        StationEntity station = stationMapper.querySingle ( stationEntity );
        return station;
    }

    @Override
    public StationEntity updateSingle (StationEntity stationEntity) {
        stationEntity.setChangeTime ( new Date () );
        boolean b = this.updateById ( stationEntity );
        if ( ! b ) {
            throw new StateException ( StateEnum.UPDATE_EXCE );
        }
//        if ( stationEntity == null ) {
//            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
//        }
//        if ( StringUtils.isBlank ( stationEntity.getId () ) ) {
//            throw new StateException ( StateEnum.PRIMARY_NULL_EXCE );
//        }
//        UpdateWrapper<StationEntity> updateWrapper = new UpdateWrapper<> ();
//        if ( StringUtils.isNotBlank ( stationEntity.getStationName () ) ) {
//            updateWrapper.set ( "stationName", stationEntity.getStationName () );
//        }
//        if ( StringUtils.isNotBlank ( stationEntity.getCoverImg () ) ) {
//            updateWrapper.set ( "coverImg", stationEntity.getCoverImg () );
//        }
//        if ( StringUtils.isNotBlank ( stationEntity.getProvinceId () ) ) {
//            updateWrapper.set ( "provinceId", stationEntity.getProvinceId () );
//        }
//        if ( StringUtils.isNotBlank ( stationEntity.getCityId () ) ) {
//            updateWrapper.set ( "cityId", stationEntity.getCityId () );
//        }
//        if ( StringUtils.isNotBlank ( stationEntity.getCountyId () ) ) {
//            updateWrapper.set ( "countyId", stationEntity.getCountyId () );
//        }
//        if ( StringUtils.isNotBlank ( stationEntity.getAddress () ) ) {
//            updateWrapper.set ( "address", stationEntity.getAddress () );
//        }
//        if ( StringUtils.isNotBlank ( stationEntity.getLongitude () ) ) {
//            updateWrapper.set ( "longitude", stationEntity.getLongitude () );
//        }
//        if ( StringUtils.isNotBlank ( stationEntity.getLatitude () ) ) {
//            updateWrapper.set ( "latitude", stationEntity.getLatitude () );
//        }
//        if ( StringUtils.isNotBlank ( stationEntity.getTimeZone () ) ) {
//            updateWrapper.set ( "timeZone", stationEntity.getTimeZone () );
//        }
//        if ( stationEntity.getStationType () != null ) {
//            updateWrapper.set ( "stationType", stationEntity.getStationType () );
//        }
//        if ( stationEntity.getSystemType () != null ) {
//            updateWrapper.set ( "systemType", stationEntity.getSystemType () );
//        }
//        if ( StringUtils.isNotBlank ( stationEntity.getCapacity () ) ) {
//            updateWrapper.set ( "capacity", stationEntity.getCapacity () );
//        }
//        if ( stationEntity.getMergeTime () != null ) {
//            updateWrapper.set ( "mergeTime", stationEntity.getMergeTime () );
//        }
//        if ( stationEntity.getMergeState () != null ) {
//            updateWrapper.set ( "mergeState", stationEntity.getMergeState () );
//        }
//        if ( StringUtils.isNotBlank ( stationEntity.getPlanUseRate () ) ) {
//            updateWrapper.set ( "planUseRate", stationEntity.getPlanUseRate () );
//        }
//        if ( StringUtils.isNotBlank ( stationEntity.getCurrencyUnit () ) ) {
//            updateWrapper.set ( "currencyUnit", stationEntity.getCurrencyUnit () );
//        }
//        if ( StringUtils.isNotBlank ( stationEntity.getUnitPrice () ) ) {
//            updateWrapper.set ( "unitPrice", stationEntity.getUnitPrice () );
//        }
//        if ( StringUtils.isNotBlank ( stationEntity.getSubsidy () ) ) {
//            updateWrapper.set ( "subsidy", stationEntity.getSubsidy () );
//        }
//        if ( StringUtils.isNotBlank ( stationEntity.getCost () ) ) {
//            updateWrapper.set ( "cost", stationEntity.getCost () );
//        }
//        if ( StringUtils.isNotBlank ( stationEntity.getDayRepayment () ) ) {
//            updateWrapper.set ( "dayRepayment", stationEntity.getDayRepayment () );
//        }
//        if ( StringUtils.isNotBlank ( stationEntity.getMerchantName () ) ) {
//            updateWrapper.set ( "merchantName", stationEntity.getMerchantName () );
//        }
//        if ( StringUtils.isNotBlank ( stationEntity.getTelPhone () ) ) {
//            updateWrapper.set ( "telPhone", stationEntity.getTelPhone () );
//        }
//        if ( StringUtils.isNotBlank ( stationEntity.getCompany () ) ) {
//            updateWrapper.set ( "company", stationEntity.getCompany () );
//        }
//        if ( StringUtils.isNotBlank ( stationEntity.getMerchantId () ) ) {
//            updateWrapper.set ( "merchantId", stationEntity.getMerchantId () );
//        }
//        if ( stationEntity.getIsUsed () != null ) {
//            updateWrapper.set ( "isUsed", stationEntity.getIsUsed () );
//        }
//        updateWrapper.eq ( "id", stationEntity.getId () );
//        stationEntity.setChangeTime ( new Date () );
//        int update = baseMapper.update ( null, updateWrapper );
//        if ( update == 0 ) {
//            throw new StateException ( StateEnum.UPDATE_EXCE );
//        }
        return stationEntity;
    }


    /**
     * 数据看板：电站状态简报
     * 1.总电站数
     * 2.接入中电站数量
     * 3.全部设备离线电站数
     * 4.部分设备离线电站数
     * 5.有报警电站数
     * @param stationEntity
     * @return
     */
    @Override
    public Map<String, Integer> dashboardStationReport (StationEntity stationEntity) {
        Map<String, Integer> map = new HashMap<> ();
        if ( stationEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        //所有电站
        stationEntity.setType ( 1 );
        List<StationEntity> stationEntities = stationMapper.dashboardStationReport ( stationEntity );
        List<DeviceEntity> deviceEntities = null;
        if ( stationEntities != null && stationEntities.size () > 0 ) {
            List<String> ids = stationEntities.stream ().map ( StationEntity :: getId ).collect ( Collectors.toList () );
            deviceEntities = deviceMapper.selectList ( new QueryWrapper<DeviceEntity> ().
                                                               in ( "stationId", ids ).
                                                               eq ( "deviceType", ConstUtil.DEVICE_TYPE_INVERTER ) );

        }
        //接入中电站数：哪些电站下没有设备
        int join = 0;
        for ( StationEntity station : stationEntities ) {
            //List<DeviceEntity> deviceEntities = deviceMapper.selectList ( new QueryWrapper<DeviceEntity> ().eq ( "stationId", station.getId () ).eq ( "deviceType", ConstUtil.DEVICE_TYPE_INVERTER ) );
            if ( deviceEntities != null && deviceEntities.size () == 0 ) {
                List<DeviceEntity> collect = deviceEntities.stream ().filter ( device -> device.getStationId ().equals ( station.getId () ) && device.getDeviceType ().equals ( ConstUtil.DEVICE_TYPE_INVERTER ) ).collect ( Collectors.toList () );
                // 当前station为接入中电站
                if ( collect != null && collect.size () > 0 ) {
                    join++;
                }
            }
        }
        map.put ( "count", stationEntities.size () );
        map.put ( "join", join );
        return map;
    }

    /**
     * 数据看板：整体发电概况
     * 1、所有电站当日发电量
     * 2、所有电站当月发电量
     * 3、所有电站当年发电量
     * 4、所有电站累计发电量
     * 5、所有电站总装机容量
     * 6、所有电站发电总功率
     * 7、所有电站功率归一化=当前发电功率/装机容量
     * @param stationEntity
     * @return
     */
    @Override
    public Map<String, Object> dashboardStationPower (StationEntity stationEntity) {
        Map<String, Object> map = new HashMap<> ();
        if ( stationEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        // 求一个商户下所有电站所有逆变器实时发电数据
        // 设置inverter_system_info分区名称
        LocalDate localDate = LocalDate.now ();
        //String yearAndMonth = localDate.getYear () + "" + ( localDate.getMonthValue () < 10 ? "0" + localDate.getMonthValue () : localDate.getMonthValue () );
        //String partitionName = "partition (p" + yearAndMonth + ")";
        //stationEntity.setPartitionName ( partitionName );
        //List<StationEntity> stationEntities = inverterElectricMapper.queryPowerGroupStation ( stationEntity );
        List<StationEntity> stationEntities = latestInverterElectricMapper.queryPowerGroupStation ( stationEntity );
        double dayPower = 0, allPower = 0, totalPower = 0;
        for ( StationEntity station : stationEntities ) {
            dayPower += Double.parseDouble ( station.getTodayEnergy () );
            allPower += station.getTotaEnergy ();
            totalPower += Double.parseDouble ( StringUtils.isBlank ( station.getGridPower () ) ? "0" : station.getGridPower () );
        }
        // 求登录用户所在商户每个电站的每个逆变器的装机容量之和
        List<DeviceEntity> deviceEntities = deviceMapper.queryPowerByMerchant ( stationEntity );
        double allCapacity = deviceEntities.stream ().mapToDouble ( p -> Double.parseDouble ( StringUtils.isBlank ( p.getPower () ) ? "0" : p.getPower () ) ).sum ();
        // 查询一个商户下所有电站所有逆变器的年度发电量
        Calendar calendar = Calendar.getInstance ();
        // 查询当月备份数据
        calendar.set ( Calendar.DAY_OF_MONTH, 1 );//本月1号
        stationEntity.setStartTime ( calendar.getTime () );
        calendar.set ( Calendar.DAY_OF_MONTH, calendar.getActualMaximum ( Calendar.DAY_OF_MONTH ) );
        int lastDayOfMonth = calendar.get ( Calendar.DAY_OF_MONTH ); //本月最后一天
        calendar.set ( Calendar.DAY_OF_MONTH, lastDayOfMonth );
        stationEntity.setEndTime ( calendar.getTime () );
        List<InverterAmountStatisticsDayEntity> inverterAmountStatisticsDayEntities = inverterAmountStatisticsDayMapper.queryAllStationAmountList ( stationEntity );
        double monthPower = inverterAmountStatisticsDayEntities.stream ().mapToDouble ( year -> Double.parseDouble ( year.getYesterdayPower () ) ).sum ();
        // 查询全年备份数据
        calendar.set ( Calendar.MONTH, 0 );//1月
        calendar.set ( Calendar.DAY_OF_MONTH, 1 );
        stationEntity.setStartTime ( calendar.getTime () );
        calendar.set ( Calendar.MONTH, 11 );//12月
        int actualMaximum = calendar.getActualMaximum ( Calendar.DATE );
        calendar.set ( Calendar.DAY_OF_MONTH, actualMaximum );
        stationEntity.setEndTime ( calendar.getTime () );
        // 查询全年总的备份数据
        inverterAmountStatisticsDayEntities = inverterAmountStatisticsDayMapper.queryAllStationAmountList ( stationEntity );
        double sum = inverterAmountStatisticsDayEntities.stream ().mapToDouble ( year -> Double.parseDouble ( year.getYesterdayPower () ) ).sum ();
        //map.put ( "powerRate", CommonUtil.divided ( totalPower, allCapacity ) );//当前功率/总装机容量*100
        map.put ( "dayPower", CommonUtil.parseDecimalPoint ( dayPower ) );
        map.put ( "monthPower", CommonUtil.parseDecimalPoint ( monthPower + dayPower ) );
        map.put ( "yearPower", CommonUtil.parseDecimalPoint ( ( sum + dayPower ) ) );
        map.put ( "allPower", CommonUtil.parseDecimalPoint ( allPower ) );
        map.put ( "allActivePower", CommonUtil.parseDecimalPoint ( totalPower ) );
        map.put ( "allCapacity", allCapacity );
        return map;
    }


    /**
     * 数据看板：整体发电历史
     * 1、某月总计发电量：2023-07-01 ~ 2023-07-31
     * 2、某年总计发电量：2023-01 ~ 2023-12
     * @param stationEntity
     * @return
     */
    @Override
    public Map<String, Double> dashboardPowerHistory (StationEntity stationEntity) {
        Map<String, Double> map = new HashMap<> ();
        // 设置inverter_system_info分区名称
        LocalDate localDate = LocalDate.now ();
        //String yearAndMonth = localDate.getYear () + "" + ( localDate.getMonthValue () < 10 ? "0" + localDate.getMonthValue () : localDate.getMonthValue () );
        //String partitionName = "partition (p" + yearAndMonth + ")";
        //stationEntity.setPartitionName ( partitionName );
        if ( stationEntity.getTimeType () == 1 ) {
            //按日期分组，求和
            List<InverterAmountStatisticsDayEntity> inverterAmountStatisticsDayEntities = inverterAmountStatisticsDayMapper.queryAllStationAmountList ( stationEntity );
            Map<Date, List<InverterAmountStatisticsDayEntity>> collect = inverterAmountStatisticsDayEntities.stream ().collect ( Collectors.groupingBy ( InverterAmountStatisticsDayEntity :: getCollectorTime ) );
            for ( Map.Entry<Date, List<InverterAmountStatisticsDayEntity>> entry : collect.entrySet () ) {
                double power = 0;
                for ( InverterAmountStatisticsDayEntity inverterAmountStatisticsDayEntity : entry.getValue () ) {
                    power += Double.parseDouble ( inverterAmountStatisticsDayEntity.getYesterdayPower () );
                }
                map.put ( CommonUtil.getDateStrFormat ( entry.getKey (), "yyyy-MM-dd" ), Double.parseDouble ( CommonUtil.parseDecimalPoint ( power ) ) );
            }
            // 当日期是本月的时候，加上今天的
            if ( CommonUtil.checkMonth ( CommonUtil.getDateStrFormat ( stationEntity.getStartTime (), "yyyy-MM" ) ) ) {
                //List<StationEntity> inverterSystemEntities = inverterElectricMapper.queryPowerGroupStation ( stationEntity );
                List<StationEntity> inverterSystemEntities = latestInverterElectricMapper.queryPowerGroupStation ( stationEntity );
                double dayPower = 0;
                for ( StationEntity inverterSystemEntity : inverterSystemEntities ) {
                    dayPower += Double.parseDouble ( inverterSystemEntity.getTodayEnergy () );
                }
                map.put ( CommonUtil.getDateStrFormat ( new Date (), "yyyy-MM-dd" ), Double.parseDouble ( CommonUtil.parseDecimalPoint ( dayPower ) ) );
            }
        } else if ( stationEntity.getTimeType () == 2 ) {
            List<InverterAmountStatisticsDayEntity> inverterAmountStatisticsDayEntities = inverterAmountStatisticsDayMapper.queryAllStationAmountList ( stationEntity );
            Map<String, List<InverterAmountStatisticsDayEntity>> collect = inverterAmountStatisticsDayEntities.stream ().collect ( Collectors.groupingBy ( InverterAmountStatisticsDayEntity :: getMonthTime ) );
            for ( Map.Entry<String, List<InverterAmountStatisticsDayEntity>> entry : collect.entrySet () ) {
                double sumByDay = entry.getValue ().stream ().mapToDouble ( allPower -> Double.parseDouble ( allPower.getYesterdayPower () ) ).sum ();
                map.put ( entry.getKey (), Double.parseDouble ( CommonUtil.parseDecimalPoint ( sumByDay ) ) ); // 按月显示发电量
            }
            // 当查询年份是今年，则加上今天的到本月数据里面
            if ( CommonUtil.checkYear ( CommonUtil.getDateStrFormat ( stationEntity.getStartTime (), "yyyy" ) ) ) {
                List<StationEntity> inverterSystemEntities = latestInverterElectricMapper.queryPowerGroupStation ( stationEntity ); // 当前商户今天所有逆变器发电实时最大值
                double power = 0;
                for ( StationEntity inverterSystemEntity : inverterSystemEntities ) {
                    power += Double.parseDouble ( inverterSystemEntity.getTodayEnergy () );
                }
                Double currMonth = map.get ( CommonUtil.getDateStrFormat ( new Date (), "yyyy-MM" ) );
                currMonth = ( currMonth == null ? 0 : currMonth ) + power;
                map.put ( CommonUtil.getDateStrFormat ( new Date (), "yyyy-MM" ), Double.parseDouble ( CommonUtil.parseDecimalPoint ( currMonth ) ) );
            }
        }
        return map;
    }


    /**
     * 查询电站子系统，当前电站下属每个逆变器的日、月、年、总发电量以及发电功率
     * 1.电站详情
     * 2.下属逆变器发电数据
     * @param stationEntity
     * @return
     */
    @Override
    public Map<String, Object> childStation (StationEntity stationEntity) {
        Map<String, Object> map = new HashMap<> ();
        if ( stationEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        if ( StringUtils.isBlank ( stationEntity.getId () ) ) {
            throw new StateException ( StateEnum.PRIMARY_NULL_EXCE );
        }
        //stationEntity = stationMapper.querySingle ( stationEntity );
        stationEntity = stationMapper.selectById ( stationEntity );
        //拿到逆变器功能，计算装机容量
        List<DeviceEntity> deviceEntities = deviceMapper.selectList ( new QueryWrapper<DeviceEntity> ().eq ( "stationId", stationEntity.getId () ) );
        double sum = deviceEntities.stream ().mapToDouble ( p -> Double.parseDouble ( ( p.getPower () == null || "".equals ( p.getPower () ) ) ? "0" : p.getPower () ) ).sum ();
        stationEntity.setCapacity ( CommonUtil.parseDecimalPoint ( sum ) );
        // 电站下属所有逆变器实时发电数据
        // 设置inverter_system_info分区名称
        LocalDate localDate = LocalDate.now ();
        String yearAndMonth = localDate.getYear () + "" + ( localDate.getMonthValue () < 10 ? "0" + localDate.getMonthValue () : localDate.getMonthValue () );
        String partitionName = "partition (p" + yearAndMonth + ")";
        //stationEntity.setPartitionName ( partitionName );
        //List<InverterElectricEntity> inverterSystemEntities = inverterElectricMapper.queryPowerGroupInverter ( stationEntity );
        List<InverterElectricEntity> inverterElectricEntities = latestInverterElectricMapper.queryPowerGroupInverter ( stationEntity );
        double dayPower = inverterElectricEntities.stream ().mapToDouble ( day -> Double.parseDouble ( day.getTodayEnergy () ) ).sum ();
        double allPower = inverterElectricEntities.stream ().mapToDouble ( all -> Double.parseDouble ( all.getTotaEnergy () ) ).sum ();
        double allActivePower = 0;
        for ( InverterElectricEntity inverterSystemEntity : inverterElectricEntities ) {
            allActivePower += Double.parseDouble ( inverterSystemEntity.getGridPower () );
        }
        // 逆变器数量
        Integer inverterNum = deviceMapper.selectCount ( new QueryWrapper<DeviceEntity> ().eq ( "stationId", stationEntity.getId () ).eq ( "deviceType", ConstUtil.DEVICE_TYPE_INVERTER ) );
        Integer monitorNum = 0;
        Integer collectorNum = deviceMapper.selectCount ( new QueryWrapper<DeviceEntity> ().eq ( "stationId", stationEntity.getId () ).eq ( "deviceType", ConstUtil.DEVICE_TYPE_COLLECTOR ) );
        // 查询一个商户下所有电站所有逆变器的年度发电量
        Calendar calendar = Calendar.getInstance ();
        // 查询当月备份数据
        calendar.set ( Calendar.DAY_OF_MONTH, 1 );//本月1号
        stationEntity.setStartTime ( calendar.getTime () );
        calendar.set ( Calendar.DAY_OF_MONTH, calendar.getActualMaximum ( Calendar.DAY_OF_MONTH ) );
        int lastDayOfMonth = calendar.get ( Calendar.DAY_OF_MONTH ); //本月最后一天
        calendar.set ( Calendar.DAY_OF_MONTH, lastDayOfMonth );
        stationEntity.setEndTime ( calendar.getTime () );
        List<InverterAmountStatisticsDayEntity> inverterAmountStatisticsDayEntities = inverterAmountStatisticsDayMapper.queryAllStationAmountList ( stationEntity );
        double monthPower = inverterAmountStatisticsDayEntities.stream ().mapToDouble ( year -> Double.parseDouble ( year.getYesterdayPower () ) ).sum ();
        // 查询全年备份数据
        calendar.set ( Calendar.MONTH, 0 );//1月
        calendar.set ( Calendar.DAY_OF_MONTH, 1 );
        stationEntity.setStartTime ( calendar.getTime () );
        calendar.set ( Calendar.MONTH, 11 );//12月
        int actualMaximum = calendar.getActualMaximum ( Calendar.DATE );
        calendar.set ( Calendar.DAY_OF_MONTH, actualMaximum );
        stationEntity.setEndTime ( calendar.getTime () );
        inverterAmountStatisticsDayEntities = inverterAmountStatisticsDayMapper.queryAllStationAmountList ( stationEntity );
        double yearPower = inverterAmountStatisticsDayEntities.stream ().mapToDouble ( year -> Double.parseDouble ( year.getYesterdayPower () ) ).sum ();
        // 实时并网数据
        map.put ( "stationEntity", stationEntity );
        map.put ( "dayPower", CommonUtil.parseDecimalPoint ( dayPower ) );
        map.put ( "monthPower", CommonUtil.parseDecimalPoint ( monthPower ) );
        map.put ( "yearPower", CommonUtil.parseDecimalPoint ( ( yearPower + dayPower ) ) );
        map.put ( "allPower", CommonUtil.parseDecimalPoint ( allPower ) );
        map.put ( "allActivePower", CommonUtil.parseDecimalPoint ( allActivePower ) );
        map.put ( "inverterNum", inverterNum );
        map.put ( "monitorNum", monitorNum );
        map.put ( "collectorNum", collectorNum );
        return map;
    }

    /**
     * 查询一个电站的历史数据
     * 日：发电量明细、发电功率明细
     * 月：每日发电量
     * 年：每月发电量
     * @param stationEntity
     * @return
     */
    @Override
    public Map<String, Object> childHistoryData (StationEntity stationEntity) {
        Map<String, Object> map = new HashMap<> ();
        // 设置inverter_system_info分区名称
        LocalDate localDate = LocalDate.now ();
        String yearAndMonth = localDate.getYear () + "" + ( localDate.getMonthValue () < 10 ? "0" + localDate.getMonthValue () : localDate.getMonthValue () );
        String partitionName = "partition (p" + yearAndMonth + ")";
        //stationEntity.setPartitionName ( partitionName );
        // 该电站今天所有逆变器此时此刻发电最大量
        List<InverterElectricEntity> inverterSystemGroupSn = latestInverterElectricMapper.queryPowerGroupInverter ( stationEntity );
        double sum = inverterSystemGroupSn.stream ().mapToDouble ( totalDayPower -> Double.parseDouble ( totalDayPower.getTodayEnergy () ) ).sum ();
        if ( stationEntity.getTimeType () == 1 ) {
            List<InverterElectricEntity> inverterSystemEntities = inverterElectricMapper.queryListByStation ( stationEntity );
            // 所有逆变器数据按每10分钟分组，求发电量之和、求有无功功率之和
            Map<Integer, List<InverterElectricEntity>> inverterGroupTime = inverterSystemEntities.stream ().collect ( Collectors.groupingBy ( o -> CommonUtil.parseToDate ( o.getCreateTime () ).get ( ChronoField.MINUTE_OF_DAY ) / 10 ) );
            for ( Map.Entry<Integer, List<InverterElectricEntity>> integerListEntry : inverterGroupTime.entrySet () ) {
                List<InverterElectricEntity> value = integerListEntry.getValue (); // 每个十分钟的数据
                // 每10分钟一组里，不同逆变器最大发电量之和
                Map<String, List<InverterElectricEntity>> collect = value.stream ().collect ( Collectors.groupingBy ( InverterElectricEntity :: getSerialNumber ) );
                double dayPowerSum = 0;
                for ( Map.Entry<String, List<InverterElectricEntity>> stringListEntry : collect.entrySet () ) {
                    List<InverterElectricEntity> inverterEntities = stringListEntry.getValue (); // 一台逆变器，找最大的
                    InverterElectricEntity inverterSystemEntity = inverterEntities.stream ().max ( Comparator.comparing ( InverterElectricEntity :: getCreateTime ) ).get ();
                    dayPowerSum += Double.parseDouble ( inverterSystemEntity.getTodayEnergy () );
                }
                double allActivePowerSum = value.stream ().mapToDouble ( allActivePower -> Double.parseDouble ( allActivePower.getGridPower () ) ).sum ();
                double allReactivePowerSum = value.stream ().mapToDouble ( allReactivePower -> Double.parseDouble ( allReactivePower.getGridPower () ) ).sum ();
                String sumPower = CommonUtil.sum ( String.valueOf ( allActivePowerSum ), String.valueOf ( allReactivePowerSum ) ); // 有功功率+无功功率
                StationEntity station = new StationEntity ();
                station.setTodayEnergy ( CommonUtil.parseDecimalPoint ( dayPowerSum ) );
                station.setGridPower ( sumPower );
                map.put ( CommonUtil.getDateStrFormat ( value.get ( value.size () - 1 ).getCreateTime (), "yyyy-MM-dd HH:mm:ss" ), station );
            }
            Map<String, List<InverterElectricEntity>> collect = inverterSystemEntities.stream ().collect ( Collectors.groupingBy ( InverterElectricEntity :: getSerialNumber ) );
            // 每日发电量之和
            double dayPower = 0;
            for ( Map.Entry<String, List<InverterElectricEntity>> stringListEntry : collect.entrySet () ) {
                InverterElectricEntity inverterSystemEntity = stringListEntry.getValue ().stream ().max ( Comparator.comparing ( InverterElectricEntity :: getCreateTime ) ).get ();
                dayPower += Double.parseDouble ( inverterSystemEntity.getTodayEnergy () );
            }
            map.put ( "dayPower", CommonUtil.parseDecimalPoint ( dayPower ) );
            //stationEntity = baseMapper.selectById ( stationEntity );
            //map.put ( "fullHour", CommonUtil.divided ( dayPower, Double.parseDouble ( stationEntity.getCapacity () ) ) );
        } else if ( stationEntity.getTimeType () == 2 ) {
            // 查询当月每天所有逆变器发电量，按天求和显示
            List<InverterAmountStatisticsDayEntity> inverterAmountStatisticsDayEntities = inverterAmountStatisticsDayMapper.queryAmountByStation ( stationEntity );
            // 根据日进行分组
            Map<String, List<InverterAmountStatisticsDayEntity>> collect = inverterAmountStatisticsDayEntities.stream ().collect ( Collectors.groupingBy ( createTime -> CommonUtil.getDateStrFormat ( createTime.getCollectorTime (), "yyyy-MM-dd" ) ) );
            double month = 0;
            for ( Map.Entry<String, List<InverterAmountStatisticsDayEntity>> entry : collect.entrySet () ) {
                double sumByDay = entry.getValue ().stream ().mapToDouble ( allPower -> Double.parseDouble ( allPower.getYesterdayPower () ) ).sum ();
                map.put ( entry.getKey (), CommonUtil.parseDecimalPoint ( sumByDay ) );
                month += sumByDay;
            }
            if ( CommonUtil.checkMonth ( CommonUtil.getDateStrFormat ( stationEntity.getStartTime (), "yyyy-MM" ) ) ) {
                // 如果查询的月份是本月，加上今天的
                month += sum;
                map.put ( CommonUtil.getDateStrFormat ( new Date (), "yyyy-MM-dd" ), sum );
            }
            map.put ( "monthPower", CommonUtil.parseDecimalPoint ( month ) ); // 当月总发电量
            //stationEntity = baseMapper.selectById ( stationEntity );
            //map.put ( "fullHour", CommonUtil.divided ( month, Double.parseDouble ( stationEntity.getCapacity () ) ) );
        } else if ( stationEntity.getTimeType () == 3 ) {
            // 查询当年的
            List<InverterAmountStatisticsDayEntity> inverterAmountStatisticsDayEntities = inverterAmountStatisticsDayMapper.queryAmountByStation ( stationEntity );
            Map<String, List<InverterAmountStatisticsDayEntity>> collect = inverterAmountStatisticsDayEntities.stream ().collect ( Collectors.groupingBy ( InverterAmountStatisticsDayEntity :: getMonthTime ) );
            double year = 0;
            for ( Map.Entry<String, List<InverterAmountStatisticsDayEntity>> entry : collect.entrySet () ) {
                double sumByDay = entry.getValue ().stream ().mapToDouble ( allPower -> Double.parseDouble ( allPower.getYesterdayPower () ) ).sum ();
                map.put ( entry.getKey (), CommonUtil.parseDecimalPoint ( sumByDay ) );
                year += sumByDay;
            }
            if ( CommonUtil.checkYear ( CommonUtil.getDateStrFormat ( stationEntity.getStartTime (), "yyyy" ) ) ) {
                // 如果查询的年份是今年，加上今天的
                year += sum;
                for ( Map.Entry<String, Object> stringStringEntry : map.entrySet () ) {
                    String month = stringStringEntry.getKey (); // 月份 2023-07
                    if ( CommonUtil.checkMonth ( month ) ) {
                        // map里面这个Entry是本月，累加今天的
                        sum += Double.parseDouble ( String.valueOf ( stringStringEntry.getValue () ) );
                    }
                }
                map.put ( CommonUtil.getDateStrFormat ( new Date (), "yyyy-MM" ), sum );
            }
            map.put ( "yearPower", CommonUtil.parseDecimalPoint ( year ) ); // 当月总发电量
            //stationEntity = baseMapper.selectById ( stationEntity );
            //map.put ( "fullHour", CommonUtil.divided ( year, Double.parseDouble ( stationEntity.getCapacity () ) ) );
        }
        return map;
    }


    /**
     * 数据看板：日满发小时排名
     * 每个电站的发电总量除以装机容量，前10名
     * 1、根据某商户某一天所有电站的发电获取列表
     * 2、当天的去发电系统表获取
     * 3、计算满发小时后排序
     * @param stationEntity {
     *                      createTime: '2023-07-12'
     *                      }
     * @return
     */
    @Override
    public List<StationEntity> dashboardFullHour (StationEntity stationEntity) {
        if ( stationEntity == null || stationEntity.getCreateTime () == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        // 不同电站某一天的发电总量
        List<StationEntity> stationEntities = latestInverterElectricMapper.queryFullHour ( stationEntity );
        // 求每个电站的满发小时=发电量/装机容量，进行排名
        for ( StationEntity station : stationEntities ) {
            String b = StringUtils.isBlank ( station.getTodayEnergy () ) ? "0" : station.getTodayEnergy ();
            String divided = CommonUtil.divided ( Double.parseDouble ( b ), station.getPower () );
            station.setFullHour ( divided );
        }
        // 针对所有电站的满发小时进行排序,取前十名
        stationEntities.sort ( Comparator.comparing ( StationEntity :: getFullHour ).reversed () );
        stationEntities = stationEntities.subList ( 0, stationEntities.size () > 10 ? 10 : stationEntities.size () );
        return stationEntities;
    }

    /**
     * 数据看板：功率归一化排名=根据电站分组，求得每个电站的所有发电功率之和/装机容量
     * 求每个电站的所有设备一天中所有发电功率之和;功率归一化=当前发电功率/装机容量
     * @param stationEntity
     * @return
     */
    @Override
    public List<StationEntity> dashboardPower (StationEntity stationEntity) {
        if ( stationEntity == null || stationEntity.getCreateTime () == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        //List<StationEntity> stationEntities = inverterElectricMapper.dashboardFullHour ( stationEntity );
        List<StationEntity> stationEntities = latestInverterElectricMapper.queryFullHour ( stationEntity );
        for ( StationEntity station : stationEntities ) {
            double sum = Double.parseDouble ( StringUtils.isBlank ( station.getGridPower () ) ? "0" : station.getGridPower () ); // 发点功率之和
            double power = station.getPower (); // 装机容量之和
            if ( power != 0 ) {
                station.setAvgActivePower ( CommonUtil.parseDecimalPoint ( sum / ( power * 1000 ) ) );
            }
        }
        // 针对所有电站的满发小时进行排序,取前十名 StationEntity :: getAvgActivePower
        stationEntities.sort ( Comparator.comparing ( StationEntity :: getAvgActivePower ).reversed () );
        stationEntities = stationEntities.subList ( 0, stationEntities.size () > 10 ? 10 : stationEntities.size () );
        return stationEntities;
    }

    @Override
    public List<StationEntity> stationDistribution (StationEntity stationEntity) {
        stationEntity.setType ( 1 );
        List<StationEntity> stationEntities = stationMapper.dashboardStationReport ( stationEntity );
        return stationEntities;
    }


    /**
     * 电站子系统：逆变器满发小时排名=每个逆变器的发电总量/电站的装机容量
     * 1.查询电站下每个逆变器的发电总量,发电功率
     * @param stationEntity
     * @return
     */
    @Override
    public List<InverterElectricEntity> inverterRanking (StationEntity stationEntity) {
        StationEntity station = baseMapper.selectById ( stationEntity );
        // 设置inverter_system_info分区名称
        LocalDate localDate = LocalDate.now ();
        String yearAndMonth = localDate.getYear () + "" + ( localDate.getMonthValue () < 10 ? "0" + localDate.getMonthValue () : localDate.getMonthValue () );
        String partitionName = "partition (p" + yearAndMonth + ")";
        //stationEntity.setPartitionName ( partitionName );
        List<InverterElectricEntity> inverterSystemEntities = inverterElectricMapper.queryPowerGroupInverter ( stationEntity );
        for ( InverterElectricEntity inverterSystemEntity : inverterSystemEntities ) {
            String divided = CommonUtil.divided ( Double.parseDouble ( inverterSystemEntity.getGridPower () ), Double.parseDouble ( station.getCapacity () ) );
            inverterSystemEntity.setFullHour ( Double.parseDouble ( divided ) );
            String avgActivePower = CommonUtil.divided ( Double.parseDouble ( inverterSystemEntity.getGridPower () ), Double.parseDouble ( station.getCapacity () ) );
            inverterSystemEntity.setAvgActivePower ( Double.parseDouble ( avgActivePower ) );
        }
        // 针对所有逆变器的满发小时进行排序,取前十名
        inverterSystemEntities.sort ( Comparator.comparing ( InverterElectricEntity :: getFullHour ).reversed () );
        inverterSystemEntities = inverterSystemEntities.subList ( 0, inverterSystemEntities.size () > 10 ? 10 : inverterSystemEntities.size () );
        return inverterSystemEntities;
    }

    /**
     * 大屏统计电站数量，按所在省份分组
     * @param stationEntity
     * @return
     */
    @Override
    public List<Map<String, Integer>> screenStationNum (StationEntity stationEntity) {
        List<Map<String, Integer>> stationEntities = stationMapper.screenStationNum ( stationEntity );
        return stationEntities;
    }

}
